/**
 * @author 黄泽毅
 */

//分页
//myData为待会要处理的数据，evit为'up'或'down'或页码，oldn为之前的页码
function decPageView(myData, evit, oldn) {
    let totalCount;//文件总数据
    totalCount = myData.list.length;
    let currentPage = 1;//用户传入当前页
    let pageSize = 4;//每一页默认4条数据
    //计算出来的
    let totalPage;//总页数

    totalPage = totalCount % pageSize == 0 ? parseInt(totalCount / pageSize) : parseInt(totalCount / pageSize) + 1;
    oldn = Number(oldn);
    if (evit === "up") {
        oldn = oldn - 1 >= 1 ? oldn - 1 : 1;
    } else if (evit === "down") {
        oldn = oldn + 1 <= totalPage ? oldn + 1 : totalPage;
    } else {
        oldn = evit
    }

    currentPage = oldn;
    //图表页清除所有a标签
    Array.from($(".num")).forEach(item => {
        item.remove();
    });

    //用来接收对象
    let start_end = pageIndex(3, Number(currentPage), totalPage);
    //改变原来数据的list数组
    //展示数据的开始索引
    let sta_Data = (currentPage - 1) * pageSize;
    myData.list.splice(0, sta_Data);
    if (myData.list.length > pageSize) {
        myData.list.splice(pageSize, myData.list.length - pageSize);
    }

    // 重新渲染页面的索引业数
    let start = Number(start_end.beginIndex);
    let end = Number(start_end.endIndex);
    for (let i = start; i <= end; i++) {
        let el = document.createElement("a");
        el.innerText = i;
        el.className = "num";
        el.href = "javascript:void(0)";
        if (i == Number(currentPage)) {
            el.classList.add("on");
        }
        let down = $(".down")[0];

        $(".pagination")[0].insertBefore(el, down);
    }
    showData(myData);
}

//监听点击事件
$(".pagination")[0].addEventListener("click", (e) => {
    let myData = getDataFromLocal("questionnaires");
    let myId = getDataFromLocal("dataId");
    let oldn = $(".on")[0].innerText;//原来的页码
    let event = e.target;
    if (event.className.indexOf("iconfont") != -1) {
        event = event.parentNode;
    }
    if (event.href != null) {
        $(".on")[0].classList.remove("on");
        if (event.getAttribute("mask") === "up") {
            decPageView(myData[myId - 1], "up", oldn)
        } else if (event.getAttribute("mask") === "down") {
            decPageView(myData[myId - 1], "down", oldn)
        } else {
            decPageView(myData[myId - 1], event.innerText, oldn)
        }
    }
});
